package com.erp;

import java.sql.*;

public class JdbcTransactionDemo {
    public static void main(String[] args) {
        String url = "jdbc:mysql://localhost:3306/transaction_demo?useSSL=false&serverTimezone=UTC";
        String user = "root";
        String password = "123456";

        Connection conn = null;
        PreparedStatement ps1 = null;
        PreparedStatement ps2 = null;

        try {
            // 1. 获取连接
            conn = DriverManager.getConnection(url, user, password);

            // 2. 关闭自动提交，开启事务
            conn.setAutoCommit(false);

            // 3. 执行SQL（A账户扣钱，B账户加钱）
            String sql1 = "UPDATE account SET balance = balance - 100 WHERE name = 'A'";
            String sql2 = "UPDATE account SET balance = balance + 100 WHERE name = 'B'";

            ps1 = conn.prepareStatement(sql1);
            ps2 = conn.prepareStatement(sql2);

            ps1.executeUpdate();
            if(true) {
                throw new Exception("转账失败");
            }
            ps2.executeUpdate();

            // 4. 提交事务
            conn.commit();
            System.out.println("转账成功，事务已提交。");

        } catch (Exception e) {
            // 5. 出现异常，回滚事务
            if (conn != null) {
                try {
                    conn.rollback();
                    System.out.println("转账失败，事务已回滚。");
                } catch (SQLException ex) {
                    ex.printStackTrace();
                }
            }
            e.printStackTrace();
        } finally {
            // 6. 关闭资源
            try {
                if (ps1 != null) ps1.close();
                if (ps2 != null) ps2.close();
                if (conn != null) conn.close();
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
        }
    }
} 